package com.jiamao.goplay.ui.discover;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;

import com.gyf.immersionbar.ImmersionBar;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.app.AppViewModelFactory;
import com.jiamao.goplay.base.BaseMVVMFragment;
import com.jiamao.goplay.bean.res.ResAddrDetail;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.databinding.DiscoverAddrDetailLayoutBinding;
import com.jiamao.goplay.ui.discover.vm.AddrDetailVM;
import com.jiamao.goplay.util.StringUtils;
import com.jiamao.goplay.view.EmptyCallback;
import com.jiamao.goplay.view.LoadingCallback;
import com.jiamao.goplay.view.LocationErrorCallback;
import com.jiamao.goplay.view.TimeoutCallback;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.callback.SuccessCallback;
import com.kingja.loadsir.core.Convertor;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.netease.nim.uikit.api.NimUIKit;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

/**
 * 地址详情
 */
public class AddrDetailFragment extends BaseMVVMFragment<DiscoverAddrDetailLayoutBinding, AddrDetailVM> {

    private LoadService loadService;
    private String id;
    private int status;
    private int sex = -1;
    private TextView tvMan,tvWuMan;
    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public AddrDetailVM initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(AddrDetailVM.class);
    }
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.discover_addr_detail_layout;
    }
//    @Nullable
//    @Override
//    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        binding = DataBindingUtil.inflate(inflater, initContentView(inflater, container, savedInstanceState), container, false);
//        //第二步：注册布局View
//        loadService = LoadSir.getDefault().register(binding.layoutContent, new Callback.OnReloadListener() {
//            @Override
//            public void onReload(View v) {
//
//                Log.d("HTML","ASDASDASDASDDSD"+   v.getId());
//
//                viewModel.getLoadInitData(id,0);
//                // viewModel.getLoadInitData();
//                // 重新加载逻辑
//            }
//        },new Convertor<Integer>() {
//            @Override
//            public Class<? extends Callback> map(Integer httpResult) {
//                Class<? extends Callback> resultCode = TimeoutCallback.class;
//
//
//                switch (httpResult) {
//                    case 0://成功回调
//                        resultCode = SuccessCallback.class;
//                        break;
//                    case 1://成功回调
//                        resultCode = LoadingCallback.class;
//                        break;
//                    case 2://成功回调
//                        resultCode = TimeoutCallback.class;
//                        break;
//                    case 3://成功回调
//                        resultCode = EmptyCallback.class;
//                        break;
//                }
//                Log.d("HTML","resultCode: "+resultCode+" httpResult:"+httpResult);
//                return resultCode;
//            }
//        });
//
//        return loadService.getLoadLayout();
//    }



    @SuppressLint("NewApi")
    @Override
    public void initData() {
        super.initData();


        Bundle mBundle = getArguments();
        if (mBundle != null) {
             id = mBundle.getString("id");

        }


        TextView tv=(TextView)binding.getRoot().findViewById(R.id.title_right);
        tv.setTextColor(getActivity().getColor(R.color.discover_nearby_goto));
        tv.setText("0人想去");
        
        sex = SPUtils.getInstance().getInt(Config.SEX);
        if (sex == 0){
            sex = 1;
        }else {
            sex = 2;
        }
        KLog.d("sex :"+sex);
        ImmersionBar.with(this). keyboardEnable(false).statusBarDarkFont(true).titleBar(binding.getRoot().findViewById(R.id.toolbar)).init();
        TextView titleTv =  binding.getRoot().findViewById(R.id.tvTitle);
        titleTv.setText("");
        binding.getRoot().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });

        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.getLoadData(0,id,sex);
            }
        });
        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getLoadData(1,id,sex);
            }
        });
        tvMan =   binding.getRoot().findViewById(R.id.btn_sex_man);
        tvWuMan =   binding.getRoot().findViewById(R.id.btn_sex_wuman);
        tvMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sex =1 ;
                updateSex(sex);
                binding.refreshLayout.autoRefresh();
            }
        });
        tvWuMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sex = 2;
                updateSex(sex);
                binding.refreshLayout.autoRefresh();
            }
        });
        updateSex(sex);
        viewModel.getLoadInitData(id,sex);

    }

    @SuppressLint("NewApi")
    private void updateSex(int sex){
        if (sex == 1){
            tvMan.setBackgroundResource(R.drawable.bg_addr_detail_switch_white_night);
            tvMan.setTextColor(getActivity().getColor(R.color.discover_addr_detail_name));
            tvWuMan.setBackgroundResource(0);
            tvWuMan.setTextColor(getContext().getColor(R.color.discover_title_hui));
        }else {
            tvWuMan.setBackgroundResource(R.drawable.bg_addr_detail_switch_white_night);
            tvWuMan.setTextColor(getContext().getColor(R.color.discover_addr_detail_name));
            tvMan.setBackgroundResource(0);
            tvMan.setTextColor(getContext().getColor(R.color.discover_title_hui));
          //  binding.refreshLayout.autoRefresh();
        }

    }
    @Override
    public void initViewObservable() {
        super.initViewObservable();

        //第二步：注册布局View
        loadService = LoadSir.getDefault().register(binding.layoutContent, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {

                Log.d("HTML","ASDASDASDASDDSD"+   v.getId());

                viewModel.getLoadInitData(id,0);
                // viewModel.getLoadInitData();
                // 重新加载逻辑
            }
        },new Convertor<Integer>() {
            @Override
            public Class<? extends Callback> map(Integer httpResult) {
                Class<? extends Callback> resultCode = TimeoutCallback.class;


                switch (httpResult) {
                    case 0://成功回调
                        resultCode = SuccessCallback.class;
                        break;
                    case 1://成功回调
                        resultCode = LoadingCallback.class;
                        break;
                    case 2://成功回调
                        resultCode = TimeoutCallback.class;
                        break;
                    case 3://成功回调
                        resultCode = EmptyCallback.class;
                        break;
                }
                Log.d("HTML","resultCode: "+resultCode+" httpResult:"+httpResult);
                return resultCode;
            }
        });

        viewModel.uc.pSwitchEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                Log.d("html","aaaaaaaaaaa"+aBoolean +" iit "+aBoolean);
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                //if (init){
                loadService.showWithConvertor(aBoolean);
                //  init = false;
//                }
//                else {
                //     binding.refresh.setRefreshing(false);
//                }
            }
        });


        viewModel.uc.startChat.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String aBoolean) {

                NimUIKit.startP2PSession(getActivity(),aBoolean);

            }
        });

        viewModel.uc.updateUICloectionStatus.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {


                    TextView gotoBtn=(TextView)binding.getRoot().findViewById(R.id.tv_goto_btn);
                    ImageView gotoImg=(ImageView)binding.getRoot().findViewById(R.id.tv_goto_img);
                    LinearLayout gotoLayout=(LinearLayout)binding.getRoot().findViewById(R.id.tv_goto_layout);
                    if (aBoolean == 0){
                        status  = 0;
                        gotoBtn.setText("想去");
                        gotoImg.setImageResource(R.mipmap.icon_goto_add);
                        gotoLayout.setBackgroundResource(R.drawable.bg_login_btn_ok);
                    }else {
                        status  = 1;
                        gotoBtn.setText("已添加");
                        gotoImg.setImageResource(R.mipmap.icon_goto_add_ytj);
                        gotoLayout.setBackgroundResource(R.drawable.bg_login_btn_default);
                    }


            }
        });
        viewModel.uc.refreshEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                binding.refreshLayout.finishRefresh();
                binding.refreshLayout.finishLoadMore();
            }
        });
        viewModel.uc.updateUI.observe(this, new Observer<ResAddrDetail>() {
            @Override
            public void onChanged(@Nullable ResAddrDetail aBoolean) {

                if (aBoolean!=null){
                    TextView tv=(TextView)binding.getRoot().findViewById(R.id.title_right);
                    tv.setText( StringUtils.formatBigNum(aBoolean.getNumTotal())+"人想去");
                    TextView tv_goto_nums=(TextView)binding.getRoot().findViewById(R.id.tv_goto_nums);

                    tv_goto_nums.setText(StringUtils.formatBigNum(aBoolean.getNum())+"个"+(sex==1?"男生":"女生")+"想去");

                    status = aBoolean.getStatus();
                    TextView gotoBtn=(TextView)binding.getRoot().findViewById(R.id.tv_goto_btn);
                    ImageView gotoImg=(ImageView)binding.getRoot().findViewById(R.id.tv_goto_img);
                    LinearLayout gotoLayout=(LinearLayout)binding.getRoot().findViewById(R.id.tv_goto_layout);
                    if (aBoolean.getStatus() == 0){
                        gotoBtn.setText("想去");
                        gotoImg.setImageResource(R.mipmap.icon_goto_add);
                        gotoLayout.setBackgroundResource(R.drawable.bg_login_btn_ok);
                    }else {
                        gotoBtn.setText("已添加");
                        gotoImg.setImageResource(R.mipmap.icon_goto_add_ytj);
                        gotoLayout.setBackgroundResource(R.drawable.bg_login_btn_default);
                    }
                }
               // binding.refreshLayout.finishRefresh();
                //binding.refreshLayout.finishLoadMore();
            }
        });


        //  loadService.showWithConvertor(httpResult);
    }


}
